
import Foundation
import SwiftUI
import AVFAudio
import NetworkExtension
import WebKit




struct VpnConfigResponse: Codable {
    let code: Int
    let msg: String
    let result: [VpnConfig]
}

enum NetworkError: Error {
    case invalidURL
    case requestFailed(String)
    case decodingFailed
}

struct VpnConfig: Codable, Identifiable {
    let converterPdfId: Int
    let converterPdfName: String
    let converterPdfUrl: String

    var id: Int { converterPdfId }
}


//获取节点接口
class NetworkManager {
   
    func fetchVpnConfig(success: @escaping ([VpnConfig]) -> Void, failure: @escaping (Error) -> Void) {
        guard let url = URL(string: vpnUrl) else {
            failure(NetworkError.invalidURL)
            return
        }
        
        let request = URLRequest(url: url)
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                failure(NetworkError.requestFailed(error.localizedDescription))
                return
            }
            
            guard let data = data else {
                failure(NetworkError.requestFailed("No data received"))
                return
            }
            
            do {
                let decoder = JSONDecoder()
                let response = try decoder.decode(VpnConfigResponse.self, from: data)
                if response.code == 200 {
                    success(response.result)
                } else {
                    failure(NetworkError.requestFailed(response.msg))
                }
            } catch {
                failure(NetworkError.decodingFailed)
            }
        }.resume()
    }
}


class Counter {
    var value = 1
    
    func currentValue() -> Int {
        return value
    }
}


let vpnConfigCounter = Counter()
let vpnConfigQueue = DispatchQueue(label: "com.example.vpnConfigQueue")

func downloadAllVPNConfigs(vpnConfigs: [VpnConfig]) {
    for config in vpnConfigs {
        downloadVPNConfig(urlString: config.converterPdfUrl)
    }
}

func downloadVPNConfig(urlString: String) {
    guard let url = URL(string: urlString) else {
        print("Invalid URL")
        return
    }
    
    let task = URLSession.shared.downloadTask(with: url) { localUrl, response, error in
        guard let localUrl = localUrl else {
            if let error = error {
                print("Download failed: \(error.localizedDescription)")
            }
            return
        }
        
        do {
            var fileContents = try String(contentsOf: localUrl, encoding: .utf8)
            fileContents = fileContents.replacingOccurrences(of: "\r\n", with: "\n")
            fileContents = fileContents.replacingOccurrences(of: "\r", with: "\n")
            
            let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            
            let newFileName = "hot\(vpnConfigCounter.currentValue()).ovpn"
            let savedUrl = documentsDirectory.appendingPathComponent(newFileName)
            
            try fileContents.write(to: savedUrl, atomically: true, encoding: .utf8)
            
            print("File downloaded, renamed, and moved to: \(savedUrl.path)")
            
            vpnConfigQueue.sync {
                vpnConfigCounter.value += 1
            }
            
        } catch {
            print("File processing error: \(error.localizedDescription)")
        }
    }
    
    task.resume()
}


func getIPAddress() -> String? {
    var address: String?
    var ifaddr: UnsafeMutablePointer<ifaddrs>?
    
    // 获取当前主机的所有接口
    if getifaddrs(&ifaddr) == 0 {
        var ptr = ifaddr
        while ptr != nil {
            let family = ptr!.pointee.ifa_addr.pointee.sa_family
            let name = String(cString: ptr!.pointee.ifa_name)
            
            // 只处理活动的 IPv4 接口
            if family == AF_INET && !name.hasPrefix("lo") { // 排除回环接口
                var addr = ptr!.pointee.ifa_addr.pointee
                var buf = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                
                if getnameinfo(&addr, socklen_t(addr.sa_len), &buf, socklen_t(buf.count), nil, 0, NI_NUMERICHOST) == 0 {
                    address = String(cString: buf)
                    break // 找到第一个有效 IP 后直接返回
                }
            }
            ptr = ptr?.pointee.ifa_next
        }
        freeifaddrs(ifaddr)
    }
    
    return address
}
